import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/foundation.dart';
import 'package:fnos_tv_desktop/core/model/categories.dart';
import 'package:fnos_tv_desktop/core/model/media_databases.dart';
import 'package:hive/hive.dart';
import 'package:window_manager/window_manager.dart';
import 'package:provider/provider.dart';
import '../core/core.dart';
import '../core/model/user_info.dart';
import '../widgets/window_buttons.dart';
import 'nav.dart';

class Application extends StatefulWidget {
  static BuildContext get navContext => Nav.navKey.currentContext!;

  static NavigatorState get navState => Nav.navKey.currentState!;

  static final RouteObserver<PageRoute> routeObserver =
      RouteObserver<PageRoute>();

  const Application({super.key});

  @override
  State<Application> createState() => _ApplicationState();
}

class _ApplicationState extends State<Application> with WindowListener {
  final rootPageKey = GlobalKey();

  @override
  void initState() {
    windowManager.addListener(this);
    super.initState();
  }

  @override
  void dispose() {
    windowManager.removeListener(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FluentApp(
      debugShowCheckedModeBanner: false,
      navigatorKey: Nav.navKey,
      navigatorObservers: [Application.routeObserver],
      theme: FluentThemeData(
        brightness: Brightness.dark,
        accentColor: Colors.blue,
        fontFamily: 'SourceHan',
        dialogTheme: const ContentDialogThemeData(
          padding: EdgeInsets.symmetric(horizontal: 18, vertical: 12),
          titleStyle: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
        buttonTheme: ButtonThemeData(
          hyperlinkButtonStyle: ButtonStyle(
            padding: WidgetStatePropertyAll(EdgeInsets.zero),
          ),
          filledButtonStyle: ButtonStyle(
            shape: WidgetStatePropertyAll(
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
            ),
          ),
          defaultButtonStyle: ButtonStyle(
            shape: WidgetStatePropertyAll(
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
            ),
          ),
        ),
      ),
      // home: const MainPage(),
      initialRoute: Nav.initialRoute,
      routes: Nav.routes,
      builder: (context, child) {
        return MultiProvider(
          providers: [
            ChangeNotifierProvider(create: (context) => UserInfo()),
            ChangeNotifierProvider(create: (context) => MediaDatabases()),
            ChangeNotifierProvider(create: (context) => Categories()),
          ],
          child: child!,
          builder: (context, child) {
            return ScaffoldPage(
              key: rootPageKey,
              padding: EdgeInsets.zero,
              content: FocusTraversalGroup(
                child: NavigationView(
                  appBar: NavigationAppBar(
                    automaticallyImplyLeading: false,
                    actions: const WindowButtons(),
                    title: DragToMoveArea(
                      child: Align(
                        alignment: Alignment.centerLeft,
                        child: Text('飞牛影视 ${Core.version}'),
                      ),
                    ),
                  ),
                  content: child,
                ),
              ),
            );
          },
        );
      },
    );
  }

  @override
  void onWindowClose() async {
    try {
      bool isPreventClose = await windowManager.isPreventClose();
      if (isPreventClose && mounted && Application.navContext.mounted) {
        showDialog(
          context: Application.navContext,
          builder: (_) {
            return ContentDialog(
              title: const Text('退出'),
              content: const Text('确认现在退出吗？'),
              actions: [
                FilledButton(
                  child: const Text('确认'),
                  onPressed: () {
                    _exitApp();
                  },
                ),
                Button(
                  child: const Text('取消'),
                  onPressed: () {
                    Navigator.pop(Application.navContext);
                  },
                ),
              ],
            );
          },
        );
      }
    } catch (e) {
      if (kDebugMode) {
        print(e);
      }
    }
  }

  void _exitApp() async {
    await Hive.close();
    await windowManager.setPreventClose(false);
    await windowManager.close();
  }
}
